<template>
  <div class="container flex-col">
    <div class="w_full flex-col">
      <div>
        <span class="title">编辑</span>
        <el-button link class="back_title" style="margin-left: 8px" @click="click_back" :icon="Back">返回人员排班列表
        </el-button>
      </div>

      <div class="comm_border" style="margin-top: 16px; padding: 16px 0;">
        <div class="flex-row">
          <div class="w_full flex-row-center">
            <span class="label_title" style="margin-left: 24px">日期</span>
            <el-date-picker v-model="data.dtStart"
                            type="date"
                            placeholder="请输入日期"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            size="large" class="date-picker"
                            style="margin-left: 12px;width: 200px"></el-date-picker>
            <span class="label_title" style="margin-left: 16px">排班类型</span>
            <el-select @change="selectChanged" size="large" style="margin-left: 8px; width: 200px;"
                       v-model="data.selectedShiftType">
              <el-option
                  v-for="(item, index) in data.listShiftType"
                  :key="index"
                  :label="item.scheduleTypeName"
                  :value="item.scheduleTypeId"
              ></el-option>
            </el-select>
            <el-button @click="click_addShiftType" :icon="Plus" circle style="margin-left: 8px"/>
            <span class="label_title" style="margin-left: 16px">班次类型</span>
            <el-select size="large" style="margin-left: 8px; width: 200px;" v-model="data.selectedShift">
              <el-option
                  v-for="(item, index) in data.listShift"
                  :key="index"
                  :label="item.scheduleShiftName"
                  :value="item.scheduleShiftId"
              ></el-option>
            </el-select>
            <el-button @click="click_addShift" :icon="Plus" circle style="margin-left: 8px"/>

          </div>

          <div class="flex-row-center">
            <el-button class="search_btn_primary" type="primary" @click="click_search"
                       style="margin-right: 24px;">查询
            </el-button>
          </div>
        </div>

      </div>
    </div>
    <div class="flex_1 comm_border flex" style="margin-top: 32px">
      <div class="flex_1 grid-container" style="padding: 16px;">
        <el-table :data="data.listUserSchedule" stripe style="width: 100%" border>
          <el-table-column prop="index" label="序号" width="60">
          </el-table-column>
          <el-table-column prop="userName" label="姓名" width="180">
          </el-table-column>
          <el-table-column :label="item" v-for="(item, index1) in data.userScheduleHeader" :key="item" align="center">
            <template #default="scope">
              <div v-for="(item2,index2) in scope.row.listScheduleShift"
                   @click="click_editSchedule(scope.row,item2)">
                <span v-if="index1==index2">{{ item2.scheduleShiftName }}  </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="w_full ">
      <div class="flex-row-center w_full"
           style="flex-direction: row-reverse ;margin-top: 14px;height: 50px;">
        <el-pagination
            v-model:current-page="pager.currentPage"
            v-model:page-size="pager.pageSize"
            :page-sizes="[10,20,30,50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pager.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, shallowRef} from "vue";
import {ElNotification} from "element-plus";
import {api_deleteExam} from "@/request/apis/examApi";
import {ExamVO} from "@/type/vo/ExamVO";
import {addDialog} from "@/components/gDialog/index";
import router from "@/router";
import msg from "@/components/msg";
import {DataBankInfoVO} from "@/type/vo/DataBankInfoVO";
import AddDataBankDialog from "@/views/DataBank/Dialogs/AddDataBankDialog.vue";
import {ScheduleTypeVO} from "@/type/vo/ScheduleTypeVO";
import {ScheduleShiftVO} from "@/type/vo/ScheduleShiftVO";
import {OfficeInfoVO} from "@/type/vo/OfficeInfoVO";
import {api_addScheduleType, api_listScheduleType} from "@/request/apis/shiftTypeApi";
import {api_listScheduleShift} from "@/request/apis/shiftApi";
import {Back, Plus} from "@element-plus/icons-vue";
import EditString from "@/views/Comm/EditString.vue";
import AddShiftDialog from "@/views/Schedule/Dialogs/AddShiftDialog.vue";
import {api_addScheduleUser, api_listScheduleUser} from "@/request/apis/shiftUserApi";
import {useUserStore} from "@/store/user";
import {UserSchedulesInfoVO} from "@/type/vo/UserSchedulesInfoVO";
import {ScheduleShiftDTVO} from "@/type/vo/ScheduleShiftDTVO";
import {ScheduleUserDto} from "@/type/dto/ScheduleUserDto";
import {dataAsString, timeStrAsTick} from "@/utils/TimeUtil";

const userStore = useUserStore()
const officeCode = userStore.userInfo.officeCode;
const data = reactive({
  dtStart: '',
  searchName: '',
  creatorName: '',
  selectStatus: -1,
  ansCount: 10,
  selectedShiftType: '',
  selectedShift: '',
  listShiftType: Array<ScheduleTypeVO>(),
  listShift: Array<ScheduleShiftVO>(),
  listUserSchedule: Array<UserSchedulesInfoVO>(),
  userScheduleHeader: Array<string>()

})
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 10,
})


onMounted(async () => {

  const dt = new Date();
  dt.setDate(dt.getDate() - 7);
  data.dtStart = dataAsString(dt, 'yyyy-MM-dd');
  console.log(data.dtStart)

  await search_shiftType();
  await search_pri();
})

const click_back = () => {
  router.back();
}
const click_editSchedule = async (item1: UserSchedulesInfoVO, item2: ScheduleShiftDTVO) => {
  if (data.selectedShift == '') {
    await msg.info('请选择一个班次')
    return;
  }
  console.log(item1);
  console.log(item2);
  console.log(item2.scheduleShiftId);
  //这个时候需要
  const dt = new Date(item2.dtScheduleShift);
  console.log(dt);
  const dtStr = dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
  if (!item2.scheduleShiftId) {
    let scheduleUser: ScheduleUserDto = {
      shiftId: data.selectedShift,
      userName: item1.userName,
      workDate: item2.dtScheduleShift,
      officeCode: officeCode,
      userId: item1.userId
    }
    let r = await api_addScheduleUser(scheduleUser);
    if (!r) {
      await msg.error("获取数据异常!");
      return;
    }
    if (r.code != 0) {
      await msg.error(`获取数据异常!  ${r.code} msg：${r.msg}`);
      return;
    }
  } else {

  }
  await search_pri();

}
const search_shiftType = async () => {

  data.listShiftType = Array<ScheduleTypeVO>();

  const r_listScheduleType = await api_listScheduleType('', officeCode);
  if (!r_listScheduleType) {
    await msg.error("数据异常");
    return;
  }
  if (r_listScheduleType.code != 0) {
    await msg.error(`数据异常!  ${r_listScheduleType.code} msg：${r_listScheduleType.msg}`);
    return;
  }
  data.listShiftType = r_listScheduleType.data;
  data.listShiftType.unshift({
    index: 0,
    officeCode: '',
    scheduleTypeId: '',
    scheduleTypeName: '全部'
  });
}

const search_shift = async () => {
  data.listShift = Array<ScheduleShiftVO>();

  const r_listScheduleShift = await api_listScheduleShift('');
  if (!r_listScheduleShift) {
    await msg.error("数据异常");
    return;
  }
  if (r_listScheduleShift.code != 0) {
    await msg.error(`数据异常!  ${r_listScheduleShift.code} msg：${r_listScheduleShift.msg}`);
    return;
  }
  data.listShift = r_listScheduleShift.data;
  data.listShift.unshift({
    createTime: 0,
    scheduleShiftId: '',
    showColor: 0,
    useDay: 0,
    index: 0,
    officeCode: '',
    scheduleTypeId: '',
    scheduleShiftName: '全部'
  });
}
const selectChanged = async (value: string) => {
  await search_shift();
  // listOption.length = 0
  // for (let i = 0; i < 2; i++) {
  //   listOption.push({
  //     optionContent: "",
  //     score: 0,
  //     checked: false,
  //   });
  // }
}


const click_detail = (index: number, row: DataBankInfoVO) => {
  try {
    router.push({
      path: '/addDataBankView',
      query: {
        dataId: row.dataId
      }
    })
  } catch (error) {
    // 处理取消操作
  }
}


const click_create = () => {
  try {
    //跳转到创建
    addDialog({
      title: "请输入名称",
      component: shallowRef(AddDataBankDialog),
      width: "800px",
      props: {},
      callBack: (dRet: boolean, dataId: string) => {
        console.log('dRet', dRet);
        console.log('dataId', dataId);
        if (dRet) {
          //跳转页面
          router.push({
            path: '/addDataBankView',
            query: {
              dataId: dataId
            }
          })
          return;
        }
        console.log(data, "data")
      }
    })
    // 处理确认操作
  } catch (error) {
    // 处理取消操作
  }

}

const click_addShiftType = () => {
  try {
    // if (data.selectedOfficeCode.length == 0) {
    //   msg.error('请选择科室!')
    //   return;
    // }
    addDialog({
      title: "新增排班类型",
      component: shallowRef(EditString),
      width: "600px",
      props: {examId: ''},
      callBack: async (dRet: boolean, strData: string) => {
        if (dRet) {
          //这里新增
          const scheduleType: ScheduleTypeVO =
              {
                scheduleTypeName: strData,
                index: 0,
                scheduleTypeId: '',
                officeCode: officeCode
              }

          const r = await api_addScheduleType(scheduleType);
          if (!r) {
            await msg.error("数据异常");
            return;
          }
          if (r.code != 0) {
            await msg.error(`数据异常!  ${r.code} msg：${r.msg}`);
            return;
          }
          await search_shiftType();
        }
      }
    })
    // 处理确认操作
  } catch (error) {
    // 处理取消操作
  }
}
const click_addShift = () => {
  try {
    // if (data.selectedOfficeCode.length == 0) {
    //   msg.error('请选择科室!')
    //   return;
    // }
    if (data.selectedShiftType.length == 0) {
      msg.error('请选择排班类型!')
      return;
    }
    addDialog({
      title: "新增班次",
      component: shallowRef(AddShiftDialog),
      width: "600px",
      props: {
        officeCode: officeCode,
        shiftTypeId: data.selectedShiftType
      },
      callBack: async (dRet: boolean) => {
        if (dRet) {
          await search_shift();
        }
      }
    })
    // 处理确认操作
  } catch (error) {
    // 处理取消操作
  }
}


const click_delete = async (exam: ExamVO) => {
  try {
    const rDialog = await msg.yesNo(
        `是否确认删除考试 ${exam.title}?`,
        '警告'
    );
    if (rDialog) {
      const r = await api_deleteExam(exam.examId);
      if (!r) {
        await msg.info('数据异常');
        return;
      }
      if (r.code != 0) {
        await msg.info(`数据异常!  ${r.code} msg：${r.msg}`);
        return;
      }
      await search_pri();
      ElNotification({
        title: '提示',
        message: '已删除!',
      })
    }
  } catch (error) {
    // 处理取消操作
  }
}

const search_pri = async () => {
  const page = pager.currentPage;
  const limit = pager.pageSize;
  console.log('dtStart', data.dtStart);
  const newDateWithAddedDays = new Date(data.dtStart);
  newDateWithAddedDays.setDate(newDateWithAddedDays.getDate() + 7);
  const r = await api_listScheduleUser(data.dtStart, dataAsString(newDateWithAddedDays, 'yyyy-MM-dd'), officeCode, page, limit);
  if (!r) {
    await msg.error("获取数据异常!");
    return;
  }
  if (r.code != 0) {
    await msg.error(`获取数据异常!  ${r.code} msg：${r.msg}`);
    return;
  }
  if (r.data.records) {
    for (let i = 0; i < r.data.records.length; i++) {
      r.data.records[i].index = i + 1;
      // r.data.records[i].createTimeStr = tickAsTimeString(r.data.records[i].createTime)
    }
  }
  data.listUserSchedule = r.data.records;
  let header = Array<string>();
  if (data.listUserSchedule.length > 0) {
    data.listUserSchedule.forEach(x => {
      x.listScheduleShift.forEach(y => {
        // console.log(y)
        if (y.scheduleShiftName == null) {
          y.scheduleShiftName = '-';
        }
      })
    })
    let listUserScheduleElement = data.listUserSchedule[0];
    if (listUserScheduleElement.listScheduleShift) {

      listUserScheduleElement.listScheduleShift.forEach(x => {

        if (x.dtScheduleShift) {
          const dt = new Date(x.dtScheduleShift);
          console.log(dt);
          header.push(dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate());
        }
      })
    }
  }
  data.userScheduleHeader = header;
  pager.total = r.data.total;
}

const click_search = async () => {
  await search_pri();
};

const handleSizeChange = async (val: number) => {
  await search_pri();
}
const handleCurrentChange = async (val: number) => {
  await search_pri();
}

</script>

<style scoped>

.grid-container {
  display: grid;
  grid-template-rows: repeat(3, auto); /* 设置3行 */
  grid-template-columns: repeat(5, auto); /* 设置3列 */
}

.cell_in_grid {
  background-color: #c6c6c6;
}


.title {
  font-size: 24px;
  font-weight: 600;
  color: #0A1629;
  line-height: 28px;
}

.back_title {
  font-size: 16px;
  font-weight: 600;
  color: #3F8CFF;
  line-height: 19px;
}

.label_title {
  font-size: 16px;
  font-weight: 400;
  color: #595959;
  line-height: 24px;
}

.date-picker {
  height: 48px;
  color: black;
  background: #FFFFFF;
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 1px solid #DCDCDC;
}

.el-scrollbar__view {
  height: calc(100% - 100px); /* 根据实际情况调整高度 */
}

.infinite-list {
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  background: black;
  margin: 10px;
  color: var(--el-color-primary);
  overflow: hidden;
}

.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}

.naireName {
  font-size: 20px;
  font-weight: 400;
  color: #0A1629;
  line-height: 24px;
}

.status {
  font-size: 16px;
  font-weight: 400;
  color: #0A1629;
  line-height: 24px;
  margin-left: 7px;
}

.btn1 {
  border: none;
  margin-left: 24px;
  width: auto;

  padding: 0;
}


</style>
